<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Loader;

/**
 * 佣金管理
 *
 * @icon fa fa-circle-o
 */
class Commission extends Backend
{
    
    /**
     * Commission模型对象
     * @var \app\admin\model\Commission
     */
    protected $model = null;
    protected $noNeedLogin = ['detail','exportTable'];

    // 数据限制
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'dealer_id';
    protected $dataLimitFieldAutoFill = false;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Commission;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $ordertime =  json_decode($this->request->get('filter'),true);
            $search_id = input('search');
            $where_sql = [];
            if ($search_id){
                $where_sql['commission.id'] = $search_id;
            }
            $dealer_id = $this->getDataLimitAdminIds();
            if ($dealer_id){
                $where_sql['dealer_id'] = $dealer_id;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['dealer'])
//                    ->where($where)
                    ->where($where_sql)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['dealer'])
//                    ->where($where)
                    ->where($where_sql)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row['test'] =  $ordertime;

                $where_con['dealer_id'] = $row['dealer_id'];
                $where_con['is_dealer'] = "1";
                $head_id = Db::name('consumer')->where($where_con)->field('id')->find()['id'];  // 经销商用户
                $where_con['is_dealer'] = "0";
                if($head_id){
                    $where_con['consumer_id'] = ['<>',$head_id];
                }
                $consumer_id = Db::name('consumer')->where($where_con)->column('id');       // 分销商用户列表

                $where_order = [];
                // 总佣金数
                $where_order['dealer_id'] = $row['dealer_id'];
//                $where_order['status'] = ['in','1,2,3'];
//                $where_order['consumer_id'] = ['<>',$head_id];
                $row['ordertime'] = '';
                if ($ordertime){
                    $betweentime = explode(' - ',$ordertime['ordertime']);
                    $row['ordertime'] = $betweentime;
                    $where_order['ordertime'] = ['between', $betweentime];
                }

                $row['commissions'] = Db::name('order')->where($where_order)->sum('commission_available');

                $row['comsumer_id'] = implode(',',$consumer_id);


                // 总分销数
                $row['distributions'] = 0;
                if ($consumer_id) {
                    $where_order['consumer_id'] = ['in',implode(',',$consumer_id)];
                    $distributions = Db::name('order')->where($where_order)->sum('commission_available');
                    $row['distributions'] = $distributions;
                }

                $row->visible(['id','dealer.id','dealer.name','distributions','commissions','ordertime','comsumer_id']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 分润详情
     */
    public function detail($dealer_id = '', $ordertime = '')
    {
        // 获取分销用户们 B
        $where_consumer['dealer_id'] = $dealer_id;
        $where_consumer['is_dealer'] = '0';
        $where_consumer['type'] = 1;
        $consumer_id_arr = Db::name('consumer')
            ->where($where_consumer)
            ->field('id,name,phone')
            ->select();
        foreach ($consumer_id_arr as &$v){
            $v['total'] = 0;
            $v['first'] = 0;
//            $where_commission['status'] = ['<>','7'];
            $where_commission = [];
            if($ordertime != 'ids')
            {
                $where_commission['ordertime'] = ['between',$ordertime];
            }
            // 获取C的id
            $c_id = Db::name('consumer')->where('consumer_id',$v['id'])->column('id');

            // 获取D的id
            if ($c_id){
                $c_id_str = implode(',',$c_id);
                $d_id = Db::name('consumer')->where('consumer_id','in',$c_id_str)->column('id');
                $d_id_str = implode(',',$d_id);
                $where_id = $c_id_str;
                if ($d_id_str){
                    $where_id = $c_id_str.','.$d_id_str;
                    $where_commission['consumer_id'] = ['in', $d_id_str];
                    $v['first'] = Db::name('order')->where($where_commission)->sum('commission_available');
                }
                $where_commission['consumer_id'] = ['in',$where_id];
                $v['total'] = Db::name('order')->where($where_commission)->sum('commission_available');
            }
        }

        $this->assign('data', $consumer_id_arr);

        return $this->view->fetch();

    }

    /**
     * 导出表格
     */
    public function exportTable($dealer_id = '', $ordertime = '')
    {
        $filename = date("YmdHis").time();
        vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objPHPExcel->getActiveSheet()->setCellValue('A1','分销商名称');
        $objPHPExcel->getActiveSheet()->setCellValue('B1','电话');
        $objPHPExcel->getActiveSheet()->setCellValue('C1','佣金总额');
        $objPHPExcel->getActiveSheet()->setCellValue('D1','1级佣金总额');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);

        // 获取分销用户们 B
        $where_consumer['dealer_id'] = $dealer_id;
        $where_consumer['is_dealer'] = '0';
        $where_consumer['type'] = 1;
        $consumer_id_arr = Db::name('consumer')
            ->where($where_consumer)
            ->field('id,name,phone')
            ->select();
        if($consumer_id_arr){
            $n = 2;
            foreach ($consumer_id_arr as &$v){
                $objPHPExcel->getActiveSheet()->setCellValue('A'.$n,$v['name']);
                $objPHPExcel->getActiveSheet()->setCellValue('B'.$n,$v['phone']);
                $v['total'] = 0;
                $v['first'] = 0;
//                $where_commission['status'] = ['in','1,2,3'];
                $where_commission = [];
                if($ordertime != 'ids')
                {
                    $where_commission['ordertime'] = ['between',$ordertime];
                }
                // 获取C的id
                $c_id = Db::name('consumer')->where('consumer_id',$v['id'])->column('id');

                // 获取D的id
                if ($c_id){
                    $c_id_str = implode(',',$c_id);
                    $d_id = Db::name('consumer')->where('consumer_id','in',$c_id_str)->column('id');
                    $d_id_str = implode(',',$d_id);
                    $where_id = $c_id_str;
                    if ($d_id_str){
                        $where_id = $c_id_str.','.$d_id_str;
                        $where_commission['consumer_id'] = ['in', $d_id_str];
                        $v['first'] = Db::name('order')->where($where_commission)->sum('commission_available');
                    }
                    $where_commission['consumer_id'] = ['in',$where_id];
                    $v['total'] = Db::name('order')->where($where_commission)->sum('commission_available');
                }
                $objPHPExcel->getActiveSheet()->setCellValue('C'.$n,$v['total']);
                $objPHPExcel->getActiveSheet()->setCellValue('D'.$n,$v['first']);
                $n++;
            }
        }


        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename='.$filename.'.xls');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

}
